<template>
  <div class="question-detail-container" v-if="question">
    <div class="question-header">
      <h1 class="question-title">{{ question.title }}</h1>
      <div class="question-meta">
        <div class="question-author">
          <el-avatar :size="40" :src="question.author.avatar"></el-avatar>
          <div class="author-info">
            <div class="author-name">{{ question.author.name }}</div>
            <div class="post-time">提问于 {{ question.createTime }}</div>
          </div>
        </div>
        <div class="question-actions">
          <el-button 
            :type="isFavorite ? 'danger' : 'default'" 
            size="small" 
            @click="toggleFavorite"
          >
            <el-icon><Star /></el-icon>
            {{ isFavorite ? '已收藏' : '收藏' }}
          </el-button>
        </div>
      </div>
      <div class="question-tags">
        <el-tag
          v-for="tag in question.tags"
          :key="tag"
          size="small"
          effect="plain"
          class="tag"
        >{{ tag }}</el-tag>
      </div>
    </div>

    <div class="question-content">
      <p>{{ question.content }}</p>
    </div>

    <div class="question-stats">
      <span class="views"><el-icon><View /></el-icon> {{ question.views }} 浏览</span>
      <span class="answers"><el-icon><ChatDotRound /></el-icon> {{ question.answers.length }} 回答</span>
    </div>

    <div class="question-answers">
      <h3>回答 ({{ question.answers.length }})</h3>
      
      <div class="answer-list">
        <div v-for="answer in question.answers" :key="answer.id" class="answer-item">
          <div class="answer-author">
            <el-avatar :size="32" :src="answer.author.avatar"></el-avatar>
            <div class="author-info">
              <div class="author-name">{{ answer.author.name }}</div>
              <div class="answer-time">{{ answer.createTime }}</div>
            </div>
            <div v-if="answer.accepted" class="accepted-tag">
              <el-tag type="success" effect="dark" size="small">已采纳</el-tag>
            </div>
          </div>
          <div class="answer-content">
            <p>{{ answer.content }}</p>
          </div>
          <div class="answer-actions">
            <el-button type="text" size="small" @click="voteAnswer(answer.id, 'up')">
              <el-icon><Top /></el-icon> {{ answer.votes > 0 ? answer.votes : '赞同' }}
            </el-button>
            <el-button type="text" size="small" @click="voteAnswer(answer.id, 'down')">
              <el-icon><Bottom /></el-icon>
            </el-button>
            <el-button 
              v-if="isAuthor && !hasAcceptedAnswer" 
              type="success" 
              size="small"
              @click="acceptAnswer(answer.id)"
            >
              采纳为最佳答案
            </el-button>
          </div>
        </div>
      </div>
      
      <div class="answer-form">
        <h4>撰写回答</h4>
        <el-form @submit.prevent="submitAnswer">
          <el-form-item>
            <el-input
              v-model="answerContent"
              type="textarea"
              :rows="6"
              placeholder="写下你的回答..."
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitAnswer" :loading="submitting">
              提交回答
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
  <div v-else class="loading-container">
    <el-skeleton :rows="10" animated />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useStore } from 'vuex';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { View, ChatDotRound, Star, Top, Bottom } from '@element-plus/icons-vue';

const store = useStore();
const route = useRoute();
const router = useRouter();
const questionId = computed(() => Number(route.params.id));
const answerContent = ref('');
const submitting = ref(false);

// 获取问题详情
onMounted(async () => {
  try {
    await store.dispatch('community/fetchQuestionDetail', questionId.value);
  } catch (error) {
    ElMessage.error('获取问题详情失败');
    console.error(error);
  }
});

// 获取问题数据
const question = computed(() => store.getters['community/currentQuestion']);

// 判断是否已收藏
const isFavorite = computed(() => 
  store.getters['community/isQuestionFavorite'](questionId.value)
);

// 判断当前用户是否是问题作者
const isAuthor = computed(() => {
  if (!question.value || !store.getters.userInfo) return false;
  return question.value.author.id === store.getters.userInfo.id;
});

// 判断是否已有被采纳的回答
const hasAcceptedAnswer = computed(() => {
  if (!question.value) return false;
  return question.value.answers.some(answer => answer.accepted);
});

// 收藏/取消收藏问题
const toggleFavorite = async () => {
  try {
    await store.dispatch('community/toggleFavoriteQuestion', questionId.value);
    ElMessage.success(isFavorite.value ? '已收藏问题' : '已取消收藏');
  } catch (error) {
    ElMessage.error('操作失败，请稍后重试');
    console.error(error);
  }
};

// 提交回答
const submitAnswer = async () => {
  if (!answerContent.value.trim()) {
    ElMessage.warning('回答内容不能为空');
    return;
  }
  
  submitting.value = true;
  try {
    await store.dispatch('community/addQuestionAnswer', {
      questionId: questionId.value,
      content: answerContent.value
    });
    
    ElMessage.success('回答已提交');
    answerContent.value = '';
  } catch (error) {
    ElMessage.error('提交失败，请稍后重试');
    console.error(error);
  } finally {
    submitting.value = false;
  }
};

// 投票回答
const voteAnswer = async (answerId, voteType) => {
  try {
    await store.dispatch('community/voteQuestionAnswer', {
      questionId: questionId.value,
      answerId,
      voteType
    });
    
    ElMessage.success(voteType === 'up' ? '已赞同' : '已反对');
  } catch (error) {
    ElMessage.error('操作失败，请稍后重试');
    console.error(error);
  }
};

// 采纳回答
const acceptAnswer = async (answerId) => {
  try {
    await store.dispatch('community/acceptQuestionAnswer', {
      questionId: questionId.value,
      answerId
    });
    
    ElMessage.success('已采纳为最佳答案');
  } catch (error) {
    ElMessage.error('操作失败，请稍后重试');
    console.error(error);
  }
};
</script>

<style lang="scss" scoped>
.question-detail-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.question-header {
  margin-bottom: 20px;
  
  .question-title {
    font-size: 24px;
    margin-bottom: 15px;
  }
  
  .question-meta {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    
    .question-author {
      display: flex;
      align-items: center;
      gap: 10px;
      
      .author-info {
        .author-name {
          font-weight: bold;
        }
        
        .post-time {
          font-size: 12px;
          color: #909399;
        }
      }
    }
  }
  
  .question-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 5px;
    margin-bottom: 15px;
  }
}

.question-content {
  margin-bottom: 20px;
  line-height: 1.6;
  
  p {
    margin-bottom: 15px;
  }
}

.question-stats {
  display: flex;
  gap: 20px;
  color: #909399;
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
  
  .views,
  .answers {
    display: flex;
    align-items: center;
    gap: 5px;
  }
}

.question-answers {
  h3 {
    font-size: 18px;
    margin-bottom: 20px;
  }
  
  .answer-list {
    margin-bottom: 30px;
    
    .answer-item {
      padding: 15px 0;
      border-bottom: 1px solid #ebeef5;
      
      &:last-child {
        border-bottom: none;
      }
      
      .answer-author {
        display: flex;
        align-items: center;
        gap: 10px;
        margin-bottom: 10px;
        
        .author-info {
          flex: 1;
          
          .author-name {
            font-weight: bold;
          }
          
          .answer-time {
            font-size: 12px;
            color: #909399;
          }
        }
        
        .accepted-tag {
          margin-left: auto;
        }
      }
      
      .answer-content {
        margin-bottom: 10px;
        line-height: 1.5;
      }
      
      .answer-actions {
        display: flex;
        gap: 15px;
      }
    }
  }
  
  .answer-form {
    h4 {
      font-size: 16px;
      margin-bottom: 15px;
    }
  }
}

.loading-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}
</style> 